package cn.hp.customer.util;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 拦截器 Spring的一个Bean(Interceptor)   过滤器 Filter(Servlet容器)  区别：
public class LoginInterceptor implements HandlerInterceptor {

    // 表示对当前请求的是否放行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断当前session中是否登录的有adminName
        Object adminName = request.getSession().getAttribute("adminName");
        // 存在登录的管理员
        if (adminName != null && adminName.toString().length() > 0){
            return true ;
        }
        // 管理员未登录 跳转登录页 请求转发 重定向
        response.sendRedirect("/admin/loginPage");
        return false ;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // 针对拦截的方法进行处理  可以重新设置模型和视图
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
